package Phaser_7;
import java.util.concurrent.Phaser;
public class 动态注册_分批任务处理 {
    public static void main(String[] args) {
        final Phaser phaser = new Phaser(1); // 初始注册数1（主线程）
        // 第一批任务
        startTasks(phaser, 3, "第一批");
        // 模拟主线程工作
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 第二批任务
        startTasks(phaser, 2, "第二批");
        phaser.arriveAndDeregister(); // 主线程退出
    }
    private static void startTasks(final Phaser phaser, int count, final String batchName) {
        for (int i = 0; i < count; i++) {
            phaser.register(); // 增加注册数
            final int taskId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println(batchName + "任务-" + taskId + " 启动");
                        Thread.sleep((long)(Math.random() * 1000));
                        System.out.println(batchName + "任务-" + taskId + " 完成阶段1");
                        phaser.arriveAndAwaitAdvance();

                        Thread.sleep((long)(Math.random() * 800));
                        System.out.println(batchName + "任务-" + taskId + " 完成阶段2");
                        phaser.arriveAndDeregister(); // 退出注册
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
